/** 
 * File-Name:QueryConstructor.java
 *
 * Created on 2011-4-7 下午12:17:36
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package com.exceptionhandler.service.crawl;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.exceptionhandler.entity.ExceptionInfo;
import com.exceptionhandler.service.exception.ExceptionFactory;

/**
 * Description:Construct Google queries using the exception information..
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-4-7 下午12:17:36
 */
public class QueryConstructor {
	private static Logger logger = Logger.getLogger(QueryConstructor.class);
	private static String prefix = "http://www.google.com/search?num=100&hl=en&q=";
	private static String suffix = "&btnG=Search&aq=f&aqi=&aql=&oq=";

	public static List<String> construct(List<ExceptionInfo> exceptionInfos) {
		List<String> queries = new ArrayList<String>();
		if (exceptionInfos != null) {
			for (ExceptionInfo exceptionInfo : exceptionInfos) {
				queries.addAll(construct(exceptionInfo));
			}
			return queries;
		} else {
			logger.error("exceptionInfos is null!!");
			return null;
		}
	}

	public static List<String> construct(ExceptionInfo exceptionInfo) {
		List<String> queries = new ArrayList<String>();
		String query1 = "\"" + exceptionInfo.getFullName() + "\"";
		String query2 = "\"" + exceptionInfo.getShortName() + "\"";
		logger.debug(query1);
		try {
			queries.add(prefix + URLEncoder.encode(query1, "UTF-8") + suffix);
			queries.add(prefix + URLEncoder.encode(query2, "UTF-8") + suffix);
		} catch (Exception e) {
			logger.error("Encoding Error!");
			e.printStackTrace();
		}
		return queries;
	}

	/**
	 * Description:
	 * 
	 * @param args
	 *            void
	 */
	public static void main(String[] args) {
		String stackTraceString = null;
		try {
			stackTraceString = FileUtils.readFileToString(new File(
					"D:\\ExceptionTest.txt"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		ExceptionInfo exceptionInfo = ExceptionFactory.create(stackTraceString);
		List<String> queries = QueryConstructor.construct(exceptionInfo);
		for (String query : queries) {
			System.out.println(query);
		}
	}

}
